package service

import (
	"errors"
	"hcy-api/structs/idp"
	"hcy-api/structs/tables"
	"idp/global"
	"idp/listener"
	"idp/repository"
)

var ClientService = new(clientService)

type clientService struct {
}

func (s clientService) FreeList(in idp.SearchClientPage) (rli []idp.ClientDto, total int64, err error) {
	var li []tables.IdpClient
	li, total, err = repository.ClientRepository.FreeList(in)
	rli = make([]idp.ClientDto, 0)
	for _, v := range li {
		item := idp.ClientDto{
			IdpClient: v,
		}
		item.IsOnline = listener.IsOnline(v.Id)
		rli = append(rli, item)
	}
	return
}

func (s clientService) List(uid int64, accountLv int) (li []tables.IdpClient, err error) {
	li, err = repository.ClientRepository.List(uid, accountLv)
	return
}

func (s clientService) Page(in idp.SearchClientPage, uid int64, accountLv int) (rli []idp.ClientDto, total int64, err error) {
	var li []tables.IdpClient
	if accountLv == tables.AccountLvForRoot {
		li, total, err = repository.ClientRepository.FindPageForRoot(in)
	} else {
		li, total, err = repository.ClientRepository.FindPage(uid, in)
	}
	rli = make([]idp.ClientDto, 0)
	for _, v := range li {
		item := idp.ClientDto{
			IdpClient: v,
		}
		item.IsOnline = listener.IsOnline(v.Id)
		rli = append(rli, item)
	}
	return
}

func (s clientService) SelectLastLog(logType string, clientId int64) (result interface{}, err error) {
	switch logType {
	case "cpu":
		return repository.WinLogRepository.FindLastCpu(clientId)
	case "memory":
		return repository.WinLogRepository.FindLastMemory(clientId)
	case "disk":
		return repository.WinLogRepository.FindLastDisk(clientId)
	case "appList":
		return repository.WinLogRepository.FindLastApp(clientId)
	case "board":
		return repository.WinLogRepository.FindLastBoard(clientId)
	case "sysAbstract":
		return repository.WinLogRepository.FindLastSysAbstract(clientId)
	case "base":
		if v, ok := global.InfoCatchMaoForIdp.Load(clientId); ok {
			obj := v.(*global.IdpCache)
			result = obj
		} else {
			err = errors.New("设备不存在")
		}
		return result, err
	default:
		return nil, errors.New("unknown logType ")
	}
}
